import { dynamicLoadComponent } from '@/utils/importUtil'
export default function dynamicLoadWidget(globalConfig: any) {
    return new Promise<Map<string, any>>(async (resolve, reject) => {
        try {
            console.group('读取配置，动态加载组件中...')
            let widgets = null
            try {
                const res = await fetch('http://localhost:5600/mock-json/components.json')
                widgets = await res.json()
            } catch (error) {
                console.groupEnd()
                return reject('读取配置文件失败')
            }

            const entries = await Promise.all(
                widgets.map(async (widget: { url: string; name: string; style: string }) => {
                    try {
                        const component = await dynamicLoadComponent(widget)
                        console.log(
                            `%c加载组件 ${widget.name} 成功`,
                            globalConfig.log.formatter.success
                        )
                        return [widget.name, component]
                    } catch (e) {
                        console.log(e)
                        console.error(
                            `%c加载组件 ${widget.name} 失败(可能vue文件有语法错误), 请求地址为 \n${widget.url}`,
                            globalConfig.log.formatter.error
                        )
                        return null
                    }
                })
            )
            const widgetMap = new Map<string, any>(entries.filter(Boolean))
            console.groupEnd()
            return resolve(widgetMap)
        } catch (e) {
            return reject('动态加载组件失败')
        }
    })
}
